import PDFDocument from 'pdfkit';
import * as fs from 'fs';
import { ScanResult } from './scanner';
import { AIResult } from './ai';

const RULE_TO_GBT = {
  'sql-injection': '6.2.1',
  'xss': '6.2.2',
  // ...可扩展更多规则与标准条款映射
};

export function exportComplianceReport(
  filePath: string,
  semgrepResults: ScanResult[],
  aiResults: AIResult[],
  outPath: string = 'compliance_report.pdf'
) {
  const doc = new PDFDocument();
  doc.pipe(fs.createWriteStream(outPath));

  doc.fontSize(18).text('AI代码漏洞合规报告', { align: 'center' });
  doc.moveDown();
  doc.fontSize(12).text(`扫描文件: ${filePath}`);
  doc.text(`生成时间: ${new Date().toLocaleString()}`);
  doc.moveDown();

  doc.fontSize(14).text('一、漏洞列表', { underline: true });
  doc.moveDown(0.5);
  doc.fontSize(12).text('【规则检测】');
  if (semgrepResults.length === 0) {
    doc.text('无');
  } else {
    semgrepResults.forEach(r => {
      const gbt = RULE_TO_GBT[r.ruleId] || '6.2.x';
      doc.text(`[${r.ruleId}] 行${r.line}: ${r.message} (标准条款: ${gbt})`);
    });
  }
  doc.moveDown(0.5);
  doc.fontSize(12).text('【AI增强检测】');
  if (aiResults.length === 0) {
    doc.text('无');
  } else {
    aiResults.forEach(r => {
      doc.text(`[${r.riskType || 'AI'}] 行${r.line}: ${r.message}`);
      if (r.suggestion) doc.text(`  修复建议: ${r.suggestion}`);
    });
  }
  doc.moveDown();

  doc.fontSize(14).text('二、修复建议', { underline: true });
  doc.moveDown(0.5);
  if (semgrepResults.length === 0 && aiResults.length === 0) {
    doc.text('无');
  } else {
    aiResults.forEach(r => {
      if (r.suggestion) doc.text(`[AI] 行${r.line}: ${r.suggestion}`);
    });
  }
  doc.moveDown();

  doc.fontSize(14).text('三、GB/T 25000.51标准符合性说明', { underline: true });
  doc.moveDown(0.5);
  doc.fontSize(11).text('本报告依据GB/T 25000.51-2016《软件工程 软件产品质量要求与评价（SQuaRE）第51部分：就绪可用软件产品（RUSP）的质量要求和测试细则》进行漏洞检测与合规性分析。检测内容涵盖功能适合性、安全性、可靠性等关键指标。');
  doc.moveDown();

  doc.fontSize(14).text('四、标准条款与检测项映射表', { underline: true });
  doc.fontSize(11);
  Object.entries(RULE_TO_GBT).forEach(([rule, gbt]) => {
    doc.text(`${rule} -> GB/T 25000.51 条款 ${gbt}`);
  });
  doc.moveDown();

  doc.fontSize(12).text('本报告由AI代码漏洞卫士自动生成。');
  doc.end();
} 